package com.itheima.web.linsener;

import com.itheima.service.store.QuestionItemService;
import com.itheima.service.store.impl.QuestionItemServiceImpl;
import lombok.extern.log4j.Log4j;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Log4j
@WebListener
public class listener implements ServletContextListener {
    private static QuestionItemService questionItemService=new QuestionItemServiceImpl();
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
                service.scheduleWithFixedDelay(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            log.info("**********************************************************************************");
                            log.info("****************************        开始清空没有题目的选项      *********************");
                            log.info("**********************************************************************************");
                            questionItemService.clean();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                },0,24, TimeUnit.HOURS);
            }
        };
        //设置执行时间
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,24);
        calendar.set(Calendar.MINUTE,00);
        calendar.set(Calendar.SECOND,00);

        Date date = calendar.getTime();
        Timer timer = new Timer();
        System.out.println(date);
        //每天的date时刻执行task, 仅执行一次
        timer.schedule(task, date);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
